/**
 * @file RegisterPage.jsx
 * @description 注册页面组件。
 */
import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { loginSuccess } from '../store/authSlice';
import toast from 'react-hot-toast';

const RegisterPage = () => {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [validated, setValidated] = useState(false);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const handleSubmit = (e) => {
    e.preventDefault();
    const form = e.currentTarget;
    if (form.checkValidity() === false || password !== confirmPassword) {
      e.stopPropagation();
      if (password !== confirmPassword) {
        toast.error('两次输入的密码不一致！');
      } else {
        toast.error('请检查并修正表单中的错误！');
      }
      setValidated(true);
      return; // 验证失败，提前返回
    }
    setValidated(true);

    // 从 localStorage 获取已存在的用户列表，如果不存在则初始化为空数组
    const existingUsers = JSON.parse(localStorage.getItem('registeredUsers')) || [];

    // 检查邮箱是否已被注册
    if (existingUsers.find(user => user.email === email)) {
      toast.error('此邮箱已被注册！');
      return;
    }

    // 模拟注册成功
    const newUser = {
      id: Date.now(), // 使用时间戳作为 mock ID
      name: fullName,
      email: email,
      password: password, // ★★★ 重要：存储密码 (在真实应用中，密码绝不能明文存储)
    };

    // 将新用户添加到用户列表并存回 localStorage
    existingUsers.push(newUser);
    localStorage.setItem('registeredUsers', JSON.stringify(existingUsers));

    // 注册成功后自动登录
    const userToLogin = { id: newUser.id, name: newUser.name, email: newUser.email };
    dispatch(loginSuccess(userToLogin));
    toast.success('注册成功并已自动登录！');
    navigate('/');
  };

  return (
    <div className="container my-3 py-3">
      <h1 className="text-center">注册</h1>
      <hr />
      <div className="row my-4 h-100 justify-content-center">
        <div className="col-md-6 col-lg-5 col-sm-8">
          <div className="card p-4 shadow">
            <form className={`needs-validation ${validated ? 'was-validated' : ''}`} noValidate onSubmit={handleSubmit}>
              <div className="mb-3">
                <label htmlFor="registerFullName">全名</label>
                <input
                  type="text"
                  className="form-control"
                  id="registerFullName"
                  placeholder="请输入您的姓名"
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  required
                />
                <div className="invalid-feedback">
                  请输入您的全名。
                </div>
              </div>
              <div className="mb-3">
                <label htmlFor="registerEmail">邮箱地址</label>
                <input
                  type="email"
                  className="form-control"
                  id="registerEmail"
                  placeholder="name@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
                <div className="invalid-feedback">
                  请输入有效的邮箱地址。
                </div>
              </div>
              <div className="mb-3">
                <label htmlFor="registerPassword">密码</label>
                <input
                  type="password"
                  className="form-control"
                  id="registerPassword"
                  placeholder="请输入密码 (至少6位)"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  minLength="6"
                />
                <div className="invalid-feedback">
                  密码至少需要6位。
                </div>
              </div>
              <div className="mb-3">
                <label htmlFor="confirmPassword">确认密码</label>
                <input
                  type="password"
                  className={`form-control ${validated && password !== confirmPassword && confirmPassword ? 'is-invalid' : ''}`}
                  id="confirmPassword"
                  placeholder="请再次输入密码"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  required
                  minLength="6"
                />
                {validated && password !== confirmPassword && confirmPassword && (
                  <div className="invalid-feedback d-block">
                    两次输入的密码不一致。
                  </div>
                )}
                 <div className="invalid-feedback">
                    请确认您的密码。
                </div>
              </div>
              <div className="my-3">
                <p>已经有账户了? <Link to="/login" className="text-decoration-underline text-info">登录</Link></p>
              </div>
              <div className="text-center">
                <button className="btn btn-dark w-100" type="submit">
                  注册
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default RegisterPage;